<template>
  <div id="inspection-rule">
  <v-header title="检查规则" :showDownloadBtn = "download" :saveShow = "save"></v-header>
    <div class="main-cont">
      <iToolbar v-on:click="handleToolClick" :buttonsObj="buttonsObj"></iToolbar>
      <el-container>
        <el-main>
          <el-table  :data="tableData">
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="ruleName" label="规则名称"></el-table-column>
            <el-table-column prop="ruleCode" label="规则编号"></el-table-column>
            <el-table-column prop="rulePattern" label="正则表达式"></el-table-column>
            <el-table-column prop="createTime" label="创建时间">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small"  v-on:click="ruleUpdate(scope.row)">修改</el-button>
                <el-button type="text" size="small"  v-on:click="isDelete(scope.row.ruleId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
          </el-pagination>
        </el-main>
      </el-container>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @close="cancel('ruleForm')" width="900px">
      <el-form :model="formData" ref="ruleForm" :rules="rules" label-position="right">
        <el-row>
          <el-col :span='12'>
            <el-form-item label="规则名称" :label-width="formLabelWidth" prop="ruleName">
              <el-input v-model="formData.ruleName" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label="规则编号" :label-width="formLabelWidth" prop="ruleCode">
              <el-input v-model="formData.ruleCode" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='12'>
            <el-form-item label="规则表达式" :label-width="formLabelWidth" prop="rulePattern">
              <el-input v-model="formData.rulePattern" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label="规则描述" :label-width="formLabelWidth" prop="ruleDesc">
              <el-input v-model="formData.ruleDesc" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset()">重置</el-button>
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click.native="ruleCreate('ruleForm', addOrUpsate)">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
  import ajax from '../../../../api/ajax/ajax'
  import api from '../../../../api/url'
  import {VHeader} from '../../../../components'
  import iToolbar from '../../../iapadmin/comm/iToolbar/iToolbar'
  import { getDateTime } from '../../../../assets/js/index'
  export default {
    name: 'inspection-rule',
    components: {
      iToolbar: iToolbar,
      VHeader
    },
    data () {
      return {
        addOrUpsate: '',
        dialogFormVisible: false,
        dialogTitle: '',
        initFormData: {},
        editData: {},
        download: false,
        save: false,
        buttonsObj: [
          {
            text: '新增',
            oprType: 'addRule'
          }
        ],
        tableData: [],
        formLabelWidth: '100px',
        formData: {
          ruleCode: '',
          ruleDesc: '',
          ruleName: '',
          rulePattern: '',
          ruleType: '00'
        },
        // 校验规则
        rules: {
          ruleName: [
            { required: true, message: '请输入规则名称', trigger: 'blur' }
          ],
          ruleCode: [
            { required: true, message: '请输入规则编号', trigger: 'blur' }
          ],
          rulePattern: [
            { required: true, message: '请输入规则表达式', trigger: 'blur' }
          ],
          ruleDesc: []
        },
        // 分页数据
        total: 0,
        currentPage: 1,
        pageSize: 10
      }
    },
    methods: {
      // 获取所有规则数据
      getAllData (pageNum = 1, pageSize = 10) {
        ajax.post(api.LISTAPIRULE + '?pageNum=' + pageNum + '&pageSize=' + pageSize, {}).then(res => {
          if (res.list.length > 0) {
            this.total = res.total
            this.pageSize = res.pageSize
            let ruleArr = res.list
            let changeArr = []
            ruleArr.forEach((item, key) => {
              item.createTime = getDateTime(new Date(item.createTime), 'ss')
              changeArr.push(item)
            })
            this.tableData = changeArr
            this.currentPage = pageNum
          } else {
            this.total = 0
            this.tableData = []
          }
        }).catch(() => {})
      },
      // 工具栏操作
      handleToolClick (opt) {
        switch (opt) {
          case 'addRule':
            this.addRule()
            break
          default:
            break
        }
      },
      // 提交保存发送请求
      savePost () {
        ajax.post(api.ADDAPIRULE, this.formData, true).then(res => {
          if (res === 'success') {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.getAllData()
            this.dialogFormVisible = false
          }
        }).catch((err) => {
          if (err.errorMsg) {
            this.$message.error(err.errorMsg)
          }
        })
      },
      // 提交更新发送请求
      saveUpdatePost () {
        ajax.post(api.MODIFYAPIRULE, this.formData).then(res => {
          if (res === 'success') {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.dialogFormVisible = false
            this.formData = this.initFormData
            this.getAllData(this.currentPage)
          }
          if (res.errorMsg) {
            this.$message.error(res.errorMsg)
          }
        }).catch(() => {})
      },
      // 提交保存新增的校验规则
      ruleCreate (formName, addOrUpsate) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (addOrUpsate === 'add') {
              this.savePost()
            } else if (addOrUpsate === 'update') {
              this.saveUpdatePost()
            }
          } else {
            return false
          }
        })
      },
      addRule () {
        this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
        this.dialogTitle = '新增检查规则'
        this.addOrUpsate = 'add'
        this.dialogFormVisible = true
      },
      cancel (formName) {
        this.formData = JSON.parse(JSON.stringify(this.initFormData))
        this.editData = JSON.parse(JSON.stringify(this.initFormData))
        this.$refs[formName].clearValidate()
        this.dialogFormVisible = false
      },
      // 删除一个规则
      ruleDelete (ruleId) {
        ajax.post(api.REMOVEAPIRULE, {ruleId: ruleId}).then(res => {
          if (res === 'success') {
            this.getAllData()
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          }
        }).catch(() => {})
      },
      // 确认是否进行删除操作
      isDelete (ruleId) {
        this.$confirm('确定要删除当前规则吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ruleDelete(ruleId)
        }).catch(err => {
          console.info(err)
        })
      },
      // 编辑当前校验规则
      ruleUpdate (ruleData) {
        this.editData = JSON.parse(JSON.stringify(ruleData))
        this.addOrUpsate = 'update'
        this.dialogTitle = '修改检查规则'
        this.formData = JSON.parse(JSON.stringify(ruleData))
        this.dialogFormVisible = true
      },
      // 切换分页
      handleCurrentChange (val) {
        this.getAllData(val)
      },
      // 重置表单
      reset () {
        this.formData = JSON.parse(JSON.stringify(this.editData))
        if (this.addOrUpsate === 'add') {
          this.$refs['ruleForm'].resetFields()
        } else {
          this.$refs['ruleForm'].clearValidate()
        }
      }
    },
    created () {
      this.getAllData()
      this.initFormData = JSON.parse(JSON.stringify(this.formData))
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #inspection-rule
    height 100%
    .main-cont
      width 100%
      height calc(100% - 62px)
      overflow: auto
      overflow-x hidden
      padding 10px
    .el-dialog
      .el-col
        padding 0 12px
    // .el-pagination
    //   padding-top 20px
    .el-select
    .el-input
      width 100%
</style>
